//
//  GrowlNotifier.m
//  Cidney
//
//  Created by Chris Karr on 1/8/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "GrowlNotifier.h"
#import "Dispatcher.h"
#import "FilterManager.h"
#import <AddressBook/AddressBook.h>

#define NOTIFICATION_NAME @"Incoming Phone Call"

@implementation GrowlNotifier

- (NSDictionary *) registrationDictionaryForGrowl
{
	NSMutableDictionary * dict = [NSMutableDictionary dictionary];
	
	NSArray * array = [NSArray arrayWithObject:NOTIFICATION_NAME];
	
	[dict setObject:array forKey:GROWL_NOTIFICATIONS_ALL];
	[dict setObject:array forKey:GROWL_NOTIFICATIONS_DEFAULT];
	
	return dict;
}
	
- (void) awakeFromNib
{
	[GrowlApplicationBridge setGrowlDelegate:self];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(update:) name:FILTERED_CALL object:nil];
}

- (void) update: (NSNotification *) msg
{
	NSMutableDictionary * userInfo = [NSMutableDictionary dictionaryWithDictionary:[msg userInfo]];
	
	ABPerson * person = [userInfo valueForKey:PERSON_KEY];
	
	NSData * icon = nil;
	NSString * desc = @"Incoming call...";
	
	NSString * name = [userInfo valueForKey:NAME_KEY];
	NSString * number = [userInfo valueForKey:NUMBER_KEY];
	
	if (person != nil)
	{
		icon = [person imageData];
		
		name = [NSString stringWithFormat:@"%@ %@", [person valueForProperty:kABFirstNameProperty], [person valueForProperty:kABLastNameProperty]];

		if ([[person valueForProperty:kABPersonFlags] boolValue])
			name = [person valueForProperty:kABOrganizationProperty];
		
		desc = [NSString stringWithFormat:@"%@\n%@", name, number];
	}
	else if (name != nil)
		desc = [NSString stringWithFormat:@"%@\n%@", name, number];
	
	[userInfo setValue:name forKey:NAME_KEY];
	[userInfo setValue:number forKey:NUMBER_KEY];

	[GrowlApplicationBridge notifyWithTitle:@"Incoming Phone Call" description:desc notificationName:NOTIFICATION_NAME
				iconData:icon priority:0 isSticky:NO clickContext:userInfo];
}

- (void) growlNotificationWasClicked:(id) clickContext
{
	NSDictionary * call = clickContext;
	
	NSString * name = [call valueForKey:NAME_KEY];
	NSString * number = [call valueForKey:NUMBER_KEY];
	
	NSString * msg = [NSString stringWithFormat:@"Should the caller '%@' (%@) be blacklisted?", name, number, nil];
	
	if (NSRunAlertPanel (NSLocalizedString (@"Blacklist Incoming Call", nil), msg, @"No", @"Yes", nil) == NSAlertAlternateReturn)
	{
		[[NSNotificationCenter defaultCenter] postNotificationName:BLACKLIST_CALL object:self userInfo:call];
	}
}

@end
